package com.czp.infosharingplatformapp.controller;

import com.czp.infosharingplatformapp.dto.CommentRequest;
import com.czp.infosharingplatformapp.dto.CommentResponse;
import com.czp.infosharingplatformapp.model.Comment;
import com.czp.infosharingplatformapp.service.CommentService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/comments") // 所有评论相关的接口路径以 /api/comments 开头
public class CommentController {

    @Autowired
    private CommentService commentService;

    // 创建评论
    @PostMapping
    public CommentResponse createComment(@Valid @RequestBody CommentRequest commentRequest) {
        Comment comment = commentService.createComment(
                commentRequest.getPostId(),
                commentRequest.getContent(),
                commentRequest.getUserId(),
                commentRequest.getParentId());

        // 将 Comment 转换为 CommentResponse
        CommentResponse response = new CommentResponse();
        response.setId(comment.getId());
        response.setContent(comment.getContent());
        response.setUsername(comment.getUser().getUsername());
        response.setCreatedAt(comment.getCreatedAt());
        response.setParentId(comment.getParent() != null ? comment.getParent().getId() : null);

        return response;
    }

    // 获取某个帖子的所有评论
    @GetMapping("/{postId}")
    public List<CommentResponse> getCommentsByPostId(@PathVariable Long postId) {
        return commentService.getCommentsByPostId(postId).stream()
                .map(comment -> {
                    CommentResponse response = new CommentResponse();
                    response.setId(comment.getId());
                    response.setContent(comment.getContent());
                    response.setUsername(comment.getUser().getUsername());
                    response.setCreatedAt(comment.getCreatedAt());
                    response.setParentId(comment.getParent() != null ? comment.getParent().getId() : null);
                    return response;
                })
                .collect(Collectors.toList());
    }

    @DeleteMapping("/{commentId}")
    public String deleteComment(@PathVariable Long commentId) {
        commentService.deleteComment(commentId);
        return "评论已成功删除";
    }
}